<template>
  <div style="width:100%">
    <div v-if="mixEditable" class="target_container">
      <el-form
        ref="targetManagement"
        :model="targetform"
        label-width="100px"
      >
      <el-row v-for="(item, index) in targetList"
          :key="index"
          class="target-item">
        <el-col v-if="index" :span="21">
          <div class="item-divider"></div>
        </el-col>
        <el-col :span="21" class="mt-10">
          <el-form-item label="目标任务:"
          :prop="index + '.mbTask'"
          :rules="{
            required: required, message: '目标任务不能为空', trigger: 'blur'
          }">
            <el-input
              v-model.trim="targetform[String(index)].mbTask"
            />
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <i
            class="el-icon-delete delete-btn"
            style=""
            @click="removeItem(index)"
          >
          </i>
        </el-col>
        <el-col :span="21">
          <el-form-item label="执行部门:"
          :prop="index + '.execOrgId'"
          :rules="{
            required: required, message: '执行部门不能为空', trigger: 'blur'
          }">
            <pm-select-org v-model="targetform[String(index)].execOrgId" :multiple="true" :entityModel.sync="entityModelArr[String(index)]" style="width: 100%"></pm-select-org>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="21">
          <el-form-item label="" prop="">
            <el-button
              plain
              icon="el-icon-plus"
              class="addTarget"
              @click="addTarget()"
            >
              新增任务
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    </div>
    <div v-else class="target_container">
      <div v-for="(target, index) in targetList" :key="index">
        <div>
          <span class="circle"></span>任务{{ index + 1 }}
        </div>
        <el-descriptions  class="margin-top" :column="2" :size="size" border>
        <!-- <template slot="title">
        </template> -->
        <el-descriptions-item :labelStyle="{width: '10%', minWidth: '100px'}" :contentStyle="{width: '40%'}">
          <template slot="label">
            目标任务{{index + 1}}
          </template>
          {{ target.mbTask }}
        </el-descriptions-item>
        <el-descriptions-item :labelStyle="{width: '10%', minWidth: '100px'}" :contentStyle="{width: '40%'}">
          <template slot="label">
            执行部门
          </template>
          {{ target.execOrgId ? entityModelArr && (Array.isArray(entityModelArr[String(index)]) && entityModelArr[String(index)].map(i =>i.name).join('、') || entityModelArr[String(index)].name) || ''  : '' }}
        </el-descriptions-item>
      </el-descriptions>
      </div>
      
    </div>
  </div>
</template>
<script>
import { cloneDeep } from 'lodash'
export default {
  name:'targetManagement',
  props:{
    // fieldid,name,type
    value: [],
    mode: {
      default: "edit", // 编辑模式和 edit， 展示模式 view
    },
    isInChildren: {
      type: Boolean,
      default: false
    },
    required: {
      type: Boolean,
      default: true
    }
  },
  computed: {
    isDesigner(){
      return this.$attrs._source === 'designer'
    },
    mixEditable() {
      return !(this.$attrs.readonly || this.$attrs.disabled) && this.mode === "edit"
    },
    dispatchProxy(){
      if (Vue.prototype.dispatchProxy) {
        return Vue.prototype.dispatchProxy(this)
      } else {
        return this.dispatch
      }
    },
  },
  data() {
    return {
      // v-for遍历对象时会出现顺序错乱的问题，所以加了list
      targetList: [{mbTask: '', execOrgId: ''}],
      targetform: {'0': {mbTask: '', execOrgId: '', __execOrgIdObject: []}},
      entityModelArr: {},
      separator: '&',
      inSeparator: '@',
      orgSeparator: ',',
      // 是否页面修改触发
      isEdit: false
    }
  },
  watch: {
    targetform: {
      deep: true,
      handler(val,oldVal) {
        let arr = []
        let targetArr = []
        for(const v in val) {
          const __execOrgIdObject = Array.isArray(this.entityModelArr[v]) && this.entityModelArr[v].map(i => {
            const { id, code, name } = i
            return {
              id, code, name
            }
          }) || val[v].__execOrgIdObject
          arr.push({
            ...val[v],
            __execOrgIdObject
          })
          targetArr.push(val[v])
        }
        console.log(arr,'==arr')
        if(!this.isEdit) {
          this.$emit('input', arr)
        }
          this.isEdit = false
        this.$set(this, 'targetList', targetArr)
      }
    },
    value: {
      immediate: true,
      // deep: true,
      async handler(value, oldVal) {
        console.log(value, oldVal,'value,=======val, oldVal')
        if (!value) {
          this.targetList= []
          this.targetform= {}
          this.entityModelArr= {}
        } else {
          let orgs = []
          let form = {}
          const valueArr = []
          console.log(this.value,'====this.value')
          this.value && this.value.forEach((v, i) => {
            // orgs是多选
            orgs.push(v.execOrgId)
            this.$set(form, String(i), {...form[String(i)], ...v})
            valueArr.push(v)
          })
          this.$set(this, 'targetform', cloneDeep(form))
          this.isEdit = true
          this.$set(this, 'targetList', valueArr)
          // 根据ids获取机构的值,回显
          if (!this.mixEditable && orgs ) {
            const orgList = await this.getOrgs(orgs) || []
            this.targetList.forEach((item, index) => {
              if (item.execOrgId) {
                const org = orgList.filter(i => item.execOrgId.includes(i.id))
                this.$set(this.entityModelArr, String(index), org)
              } else {
                this.$set(this.entityModelArr, String(index), null)
              }
            })
          }
        }
      }
    }
  },
  async mounted(){
  },
  methods: {
    removeItem(index) {
      this.targetList.splice(index, 1)
      const targetform = cloneDeep(this.targetform)
      delete targetform[String(index)]
      delete this.entityModelArr[String(index)]
      let arr = []
      for(const v in targetform) {
          arr.push(targetform[v])
        }
      this.$emit('input',arr)
    },
    addTarget() {
      this.targetList.push({mbTask: '', execOrgId: ''})
      this.$set(this.targetform, `${this.targetList.length - 1}`, {mbTask: '', execOrgId: ''})
    },
    async getOrgs(orgs) {
      const resp = await this.dispatchProxy(Vue.prototype.Controllers.OrgController.queryOrgByIds, {
        isFirst: '1', //不查询子机构
        ids: orgs.join(',')
      })
      if (!resp.error) {
        return resp.data
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.target_container {
  width: 100%;
  .circle {
    display: inline-block;
    height: 7px;
    width: 7px;
    border-radius: 4px;
    background: #409eff;
    margin: 1px 4px;
  }
  .delete-btn {
    font-size: 22px;
    line-height: 49px;
    margin-left: 15px;
    cursor: pointer;
    color: #b6b2b2;
  }
  .addTarget {
    width: 100%;
    margin-top: 5px;
  }
  .item-divider {
    width: 100%;
    height: 1px;
    background: linear-gradient(
        to left,
        transparent 0%,
        transparent 50%,
        #b6b2b2 50%,
        #b6b2b2 100%
    );
    background-size: 10px 1px; /* 第一个参数控制虚线的间隙（利用的是图片的放大效果一样），第二个参数控制虚线的粗细 */
    background-repeat: repeat-x;
    background-position: top;
    margin: 15px 30px;
  }
}
</style>